package com.camel.base.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.camel.base.entity.BusinessCenterQueryParams;
import com.camel.base.entity.BusinessCenterQueryResult;
import com.camel.base.entity.BusinessCenterResult;
import com.camel.base.entity.MyConnection;
import com.camel.base.feign.SysParamService;
import com.camel.base.model.TbApi;
import com.camel.base.model.TbColumn;
import com.camel.base.model.TbDatasource;
import com.camel.base.model.TbDictValue;
import com.camel.base.service.*;
import com.camel.base.utils.DBUtils;
import com.camel.base.utils.StringUtils;
import com.camel.core.entity.Result;
import com.camel.core.exceptions.CustomException;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/WMCenter")
public class ApiController {

    @Resource
    private TbApiService<TbApi> apiService;

    @Resource
    private TbDatasourceService<TbDatasource> datasourceService;

    @Resource
    private TbColumnService<TbColumn> columnService;

    @Resource
    private TbDictValueService<TbDictValue> dictValueService;

    @Resource
    private SysParamService paramService;

    private TbDatasource datasource;

    private List<TbColumn> list;

    public static String[] SP_URLS = {"/WMCenter/orgService/safePersonInfo/find"};

    public static final String LIST_JSON_STR = "LIST(JSON)";

    public static final String METHOD_ADD = "add";

    public static final String METHOD_UPDATE = "update";

    public static final String METHOD_DELETE = "delete";

    public static final String METHOD_FIND = "find";

    @PostMapping("/Organize/org/virtualOrg/search")
    public Object virtualOrgSearch(@RequestBody String params) {
        Result byCode = paramService.getByCode("VIRTUALORG_SEARCH");
        Object d = byCode.getData();
        if (!ObjectUtils.isEmpty(d)) {
            LinkedHashMap d1 = (LinkedHashMap) d;
            return d1.get("pvalue");
        }
        return null;
    }

//    /**
//     * 模拟工号获取监理单位信息
//     *
//     * @return
//     */
//    @PostMapping("/Organize/enterprise/record/findJLOrgAndDeptByUserNo")
//    public String findJLOrgAndDeptByUserNo(@RequestBody JSONObject data) throws IOException {
//        Result byCode = paramService.getByCode("FIND_JLORG_AND_DEPT_BY_USERNO");
//        Object d = byCode.getData();
//        LinkedHashMap<String, String> d1 = (LinkedHashMap) d;
//        JSONObject object = JSON.parseObject(d1.get("pvalue"));
//        return JSON.toJSONString(object);
//    }


//    /**
//     * 模拟工号获取监理队伍信息
//     *
//     * @return
//     */
//    @PostMapping("/Organize/enterprise/record/findDeptDTOSByOrgNo")
//    public String findDeptDTOSByOrgNo(@RequestBody JSONObject data) throws IOException {
//        Result byCode = paramService.getByCode("FIND_DEPTDTOS_BY_ORGNO");
//        Object d = byCode.getData();
//        LinkedHashMap<String, String> d1 = (LinkedHashMap) d;
//        JSONObject object = JSON.parseObject(d1.get("pvalue"));
//        return JSON.toJSONString(object);
//    }
//
//
//    @PostMapping("/Organize/workProject/queryListProject")
//    public BusinessCenterResult query(@RequestBody BusinessCenterQueryParams queryParams) throws IOException {
//        Result byCode = paramService.getByCode("WORK_PROJECT");
//        Object d = byCode.getData();
//        LinkedHashMap<String, String> d1 = (LinkedHashMap) d;
//        JSONObject object = JSON.parseObject(d1.get("pvalue"));
//        JSONArray result = object.getJSONArray("result");
//
//        String compayKindCode = "";
//        String projectName = "";
//        List<BusinessCenterFilter> filters = queryParams.getFilters();
//        if (!CollectionUtils.isEmpty(filters)) {
//            for (BusinessCenterFilter filter : filters) {
//                if (org.apache.commons.lang3.StringUtils.equals(filter.getFieldName(), "enterpriseType")) {
//                    compayKindCode = filter.getFieldValue();
//                }
//                if (org.apache.commons.lang3.StringUtils.equals(filter.getFieldName(), "projectName")) {
//                    projectName = filter.getFieldValue();
//                }
//            }
//        }
//        List<JSONObject> collect = result.toJavaList(JSONObject.class);
//        if (org.apache.commons.lang3.StringUtils.isNotBlank(compayKindCode)) {
//            String finalCompayKindCode = compayKindCode;
//            collect = collect.stream().filter(e ->
//                    org.apache.commons.lang3.StringUtils.equals(finalCompayKindCode, e.getString("compayKindCode"))
//            ).collect(Collectors.toList());
//        }
//
//        if (org.apache.commons.lang3.StringUtils.isNotBlank(projectName)) {
//            String finalProjectName = projectName;
//            collect = collect.stream().filter(e -> org.apache.commons.lang3.StringUtils.equals(finalProjectName, e.getString("projectName"))
//            ).collect(Collectors.toList());
//        }
//
//        BusinessCenterResult res = BusinessCenterResult.success(collect);
//        res.put("totalResult", collect.size());
//        return res;
//    }

    @RequestMapping("/**")
    public Object doRequest(HttpServletRequest request, HttpServletResponse response, @RequestBody String params) throws SQLException {
        String requestUri = request.getRequestURI();
        String method = request.getMethod();
        requestUri = requestUri.substring(5);
        if (ArrayUtils.contains(SP_URLS, requestUri)) {
            return BusinessCenterResult.success(spUrlHandler(JSONObject.parseObject(params)));
        }
        TbApi api = apiService.getOne(new QueryWrapper<TbApi>().eq("request_url", requestUri));


        if (!ObjectUtils.isEmpty(api) && api.getRequestMethod().equals(method)) {
            datasource = datasourceService.getById(api.getSourceId());
            if (ObjectUtils.isEmpty(datasource)) {
                throw new CustomException("来自模拟中台的提示: 数据源不正确,请检查后操作");
            }
            list = columnService.list(new QueryWrapper<TbColumn>()
                    .eq("source_id", datasource.getId())
                    .eq("schema_name", api.getSchemaName())
                    .eq("table_name", api.getTableName()));
            if (api.getRequestParams().equalsIgnoreCase(LIST_JSON_STR)) {
                return BusinessCenterResult.success(handleMethod(JSONArray.parseArray(params), api));
            } else {
                return BusinessCenterResult.success(handleMethod(JSONObject.parseObject(params), api));
            }

        } else {
            response.setStatus(404);
            throw new CustomException("来自模拟中台的提示: 找不到正确的接口路径: [" + requestUri + "]");
        }
    }

    public Object spUrlHandler(JSONObject params) {
        ClassPathResource resource = new ClassPathResource("analog/persons-access.txt");
        InputStream inputStream = null;
        try {
            inputStream = resource.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String str = new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining(System.lineSeparator()));
        JSONObject json = JSONObject.parseObject(str);
        JSONArray result = json.getJSONArray("result");
        List<Object> persons = result.stream().collect(Collectors.toList());
        Integer page = params.getInteger("page");
        Integer perPage = params.getInteger("perPage");
        if (page != null && perPage != null) {
            // 手动分页
            //起始下标
            int fromIndex = perPage * (page - 1);
            //终止下标
            int toIndex = fromIndex + perPage;
            int total = persons.size();
            if (toIndex >= total) {
                toIndex = total;
            }
            persons = persons.subList(fromIndex, toIndex);
        }
        JSONObject obj = new JSONObject();
        obj.put("root", persons);
        json.put("result", obj);
        return json.toJSONString();
    }

    public Object handleMethod(JSONObject params, TbApi api) throws SQLException {
        if (api.getRequestUrl().endsWith(METHOD_ADD) || "单例新增".equals(api.getRequestName())) {
            addOne(params, api);
            return null;
        }
        if (api.getRequestUrl().endsWith(METHOD_UPDATE) || "按主键修改".equals(api.getRequestName())) {
            updateById(params, api);
            return null;
        }
        if (api.getRequestUrl().endsWith(METHOD_DELETE) || "按主键删除".equals(api.getRequestName())) {
            deleteById(params, api);
            return null;
        }
        if (api.getRequestUrl().endsWith(METHOD_FIND) || "分页查询".equals(api.getRequestName())) {
            return pageQuery(params, api);
        }
        return null;
    }

    public Object handleMethod(JSONArray params, TbApi api) throws SQLException {
        if (api.getRequestUrl().endsWith(METHOD_ADD) || api.getRequestName().contains("新增")) {
            doExcuteSql(params, (param) -> {
                addOne(param, api);
            });
        }
        if (api.getRequestUrl().endsWith(METHOD_UPDATE) || api.getRequestName().contains("修改")) {
            doExcuteSql(params, (param) -> {
                updateById(param, api);
            });
        }
        if (api.getRequestUrl().endsWith(METHOD_DELETE) || api.getRequestName().contains("删除")) {
            doExcuteSql(params, (param) -> {
                deleteById(param, api);
            });
        }
        return null;
    }

    public void doExcuteSql(JSONArray params, IexceteSql toExcute) throws SQLException {
        for (int i = 0; i < params.size(); i++) {
            JSONObject param = params.getJSONObject(i);
            toExcute.doExceute(param);
        }
    }

    /**
     * 分页查询
     *
     * @param params 参数
     */
    public Object pageQuery(JSONObject params, TbApi api) throws SQLException {
        StringBuffer sbList = new StringBuffer("SELECT ");
        StringBuffer sbCount = new StringBuffer("SELECT ");
        sbList.append(baseQuerySql(list));
        sbCount.append(" count(1) totalNum ");
        if (sbList.toString().endsWith(",")) {
            sbList = new StringBuffer(sbList.substring(0, sbList.length() - 1));
        }
        sbList.append(" FROM ").append(api.getSchemaName()).append(".").append(api.getTableName());
        sbCount.append(" FROM ").append(api.getSchemaName()).append(".").append(api.getTableName());
        // Filter
        JSONArray filters = params.getJSONArray("filters");
        if (!CollectionUtils.isEmpty(filters)) {
            StringBuffer whereFilter = buildFilter(filters);
            sbList.append(whereFilter);
            sbCount.append(whereFilter);
        }
        // 排序
        if (StringUtils.isNotEmpty(params.getString("orderBy"))) {
            sbList.append(" order by ");
            String orderByStr = params.getString("orderBy");
            orderByStr = orderByStr.trim();
            String[] strings = orderByStr.split(",");
            Iterator<String> iterator = Arrays.stream(strings).iterator();
            while (iterator.hasNext()) {
                String s = iterator.next();
                if (s.trim().contains(" ")) {
                    String[] split = s.trim().split(" ");
                    String s1 = split[0];
                    TbColumn columnBySaveAs = getColumnBySaveAs(list, s1);
                    if (s1.endsWith("Name") && !"equipmentName".equalsIgnoreCase(s1)) {
                        s1 = s1.replace("Name", "");
                    }
                    if (ObjectUtils.isEmpty(columnBySaveAs)) {
                        throw new RuntimeException("来自模拟中台的提示: 没有找到作为排序的字段 [" + s1 + "]");
                    } else {
                        sbList.append(" ").append(columnBySaveAs.getColumnName());
                    }
                    sbList.append(" ");
                    if (split.length > 1) {
                        sbList.append(split[1]);
                    }
                    sbList.append(" ");
                } else {
                    TbColumn columnBySaveAs = getColumnBySaveAs(list, s);
                    if (ObjectUtils.isEmpty(columnBySaveAs)) {
                        sbList.append(" ").append(s);
                    } else {
                        sbList.append(" ").append(columnBySaveAs.getColumnName());
                    }
                    sbList.append(" ");
                    sbList.append("asc").append(" ");
                }
                if (iterator.hasNext()) {
                    sbList.append(" , ");
                }

            }
        }
        // 分页
        if (StringUtils.isNotEmpty(params.getString("page")) && StringUtils.isNotEmpty(params.getString("perPage"))) {
            String pageStr = params.getString("page");
            String perPageStr = params.getString("perPage");
            int startIndex = (Integer.parseInt(pageStr) - 1) * Integer.parseInt(perPageStr);
            sbList.append(" limit ").append(Integer.parseInt(perPageStr)).append(" offset ").append(startIndex);
        } else {
            throw new CustomException("来自模拟中台的提示: 参数[page][perPage]不能为空");
        }
        MyConnection connect = new DBUtils().getConnect(datasource);
        List<JSONObject> jsonObjects = connect.excuteQuery(sbList.toString());
        Long aLong = connect.excuteQueryForNumber(sbCount.toString());
        BusinessCenterQueryResult<JSONObject> businessCenterQueryResult = new BusinessCenterQueryResult<>();
        businessCenterQueryResult.setTotalProperty(aLong.intValue());
        if (!CollectionUtils.isEmpty(jsonObjects) && jsonObjects.size() > 2000) {
            businessCenterQueryResult.setRoot(jsonObjects.subList(0, 2000));
            doSetEnums(list, jsonObjects.subList(0, 2000));
            return businessCenterQueryResult;
        }
        doSetEnums(list, jsonObjects);
        businessCenterQueryResult.setRoot(jsonObjects);
        return businessCenterQueryResult;
    }

    public void doSetEnums(List<TbColumn> list, List<JSONObject> jsonObjects) {
        for (TbColumn tbColumn : list) {
            if (!ObjectUtils.isEmpty(tbColumn.getDictType())) {
                for (JSONObject jsonObject : jsonObjects) {
                    String keyWord;
                    if (StringUtils.isNotEmpty(tbColumn.getColumnSaveAs())) {
                        keyWord = tbColumn.getColumnSaveAs();
                    } else {
                        keyWord = tbColumn.getColumnName();
                    }
                    String val = jsonObject.getString(keyWord);
                    if (StringUtils.isEmpty(val)) {
                        continue;
                    }
                    TbDictValue tbDictValue = selectEnum(Integer.parseInt(tbColumn.getDictType()), val);
                    jsonObject.put(keyWord + "_Name", tbDictValue);
                }
            }
        }
    }

    public TbDictValue selectEnum(Integer typeId, String val) {
        return dictValueService.selectEnumWithRedis(typeId, val);
    }

    /**
     * 单例新增
     *
     * @param params 参数
     */
    public void addOne(JSONObject params, TbApi api) throws SQLException {
        TbDatasource datasource = datasourceService.getById(api.getSourceId());

        StringBuffer addSql = new StringBuffer("INSERT INTO ");
        addSql.append(api.getSchemaName()).append(".").append(api.getTableName());
        Set<String> strings = params.keySet();

        ArrayList<String> keys = new ArrayList<>(strings);

        addSql.append("(");
        Iterator<String> keyIterator = keys.iterator();
        while (keyIterator.hasNext()) {
            String next = keyIterator.next();
            TbColumn column = getColumnBySaveAs(list, next);
            if (ObjectUtils.isEmpty(column)) {
                throw new CustomException("来自模拟中台的提示: 请求:[" + api.getRequestUrl() + "]中字段[" + next + "] 不存在!");
            }
            addSql.append(column.getColumnName());
            if (keyIterator.hasNext()) {
                addSql.append(", ");
            }
        }
        addSql.append(") ");
        addSql.append("VALUES").append("(");
        Iterator<String> valIterator = keys.iterator();
        while (valIterator.hasNext()) {
            String next = valIterator.next();
            TbColumn column = getColumnBySaveAs(list, next);
            if (ObjectUtils.isEmpty(column)) {
                throw new CustomException("来自模拟中台的提示: 请求:[" + api.getRequestUrl() + "]中字段[" + next + "] 不存在!");
            }
            addSql.append("'");
            String val = params.getString(column.getColumnSaveAs());
            if (StringUtils.isNotEmpty(val) && val.contains("'")) {
                val = val.replaceAll("'", "''");
            }
            addSql.append(val);
            addSql.append("'");
            if (valIterator.hasNext()) {
                addSql.append(", ");
            }
        }
        addSql.append(")");
        MyConnection connect = new DBUtils().getConnect(datasource);
        try {
            connect.excute(addSql.toString());
        } catch (Exception e) {
            throw new CustomException("来自模拟中台的提示: " + e.getMessage());
        }
    }

    /**
     * 按主键修改
     *
     * @param params 参数
     */
    public void updateById(JSONObject params, TbApi api) throws SQLException {
        TbDatasource datasource = datasourceService.getById(api.getSourceId());
        // 查询表主键
        String primaryKey = datasourceService.primaryKey(datasource, api.getSchemaName(), api.getTableName());
        List<TbColumn> columns = columnService.list(new QueryWrapper<TbColumn>()
                .eq("source_id", datasource.getId())
                .eq("schema_name", api.getSchemaName())
                .eq("table_name", api.getTableName())
                .eq("column_name", primaryKey));
        if (CollectionUtils.isEmpty(columns)) {
            throw new CustomException("来自模拟中台的提示: 未保存主键");
        }
        if (columns.size() > 1) {
            throw new CustomException("来自模拟中台的提示: 保存的主键不唯一");
        }
        // 保存的主键
        TbColumn primaryKeyColumn = columns.get(0);
        StringBuffer addSql = new StringBuffer("UPDATE ");
        addSql.append(api.getSchemaName()).append(".").append(api.getTableName());
        addSql.append(" SET ");
        Set<String> strings = params.keySet();
        ArrayList<String> keys = new ArrayList<>(strings);
        Iterator<String> keyIterator = keys.iterator();
        StringBuffer sbSet = new StringBuffer();
        while (keyIterator.hasNext()) {
            String next = keyIterator.next();
            TbColumn column = getColumnBySaveAs(list, next);
            if (ObjectUtils.isEmpty(column)) {
                throw new CustomException("来自模拟中台的提示: 请求:[" + api.getRequestUrl() + "]中字段[" + next + "] 不存在!");
            }
            String paramsValue = params.getString(next);
            if (StringUtils.isNotEmpty(paramsValue)) {
                if (primaryKeyColumn.getColumnSaveAs().equalsIgnoreCase(next)
                        || primaryKeyColumn.getColumnName().equalsIgnoreCase(next)) {
                    continue;
                }
                sbSet.append(column.getColumnName());
                sbSet.append("=");
                sbSet.append("'");
                sbSet.append(paramsValue);
                sbSet.append("'");
                if (keyIterator.hasNext()) {
                    sbSet.append(", ");
                }
            }
        }

        if (StringUtils.isEmpty(sbSet)) {
            throw new CustomException("来自模拟中台的提示: 无效的参数");
        }
        addSql.append(" " + sbSet.toString() + " WHERE");
        addSql.append(primaryKeyColumn.getColumnName());
        addSql.append(" = ");
        addSql.append("'");
        if (StringUtils.isNotEmpty(primaryKeyColumn.getColumnSaveAs())) {
            addSql.append(params.getString(primaryKeyColumn.getColumnSaveAs()));
        } else {
            addSql.append(params.getString(primaryKeyColumn.getColumnName()));
        }
        addSql.append("'");
        MyConnection connect = new DBUtils().getConnect(datasource);
        try {
            connect.excute(addSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("来自模拟中台的提示: " + e.getMessage());
        }
    }

    /**
     * 按主键删除
     *
     * @param params 参数
     */
    public void deleteById(JSONObject params, TbApi api) throws SQLException {
        TbDatasource datasource = datasourceService.getById(api.getSourceId());
        // 查询表主键
        String primaryKey = datasourceService.primaryKey(datasource, api.getSchemaName(), api.getTableName());
        List<TbColumn> columns = columnService.list(new QueryWrapper<TbColumn>()
                .eq("source_id", datasource.getId())
                .eq("schema_name", api.getSchemaName())
                .eq("table_name", api.getTableName())
                .eq("column_name", primaryKey));

        if (CollectionUtils.isEmpty(columns)) {
            throw new CustomException("来自模拟中台的提示: 未保存主键");
        }

        if (columns.size() > 1) {
            throw new CustomException("来自模拟中台的提示: 保存的主键不唯一");
        }

        // 保存的主键
        TbColumn primaryKeyColumn = columns.get(0);

        StringBuffer deleteSb = new StringBuffer("DELETE FROM ");
        deleteSb.append(api.getSchemaName()).append(".").append(api.getTableName());
        if (params.containsKey(primaryKeyColumn.getColumnSaveAs()) || params.containsKey(primaryKeyColumn.getColumnName())) {
            deleteSb.append(" WHERE ");
            deleteSb.append(primaryKeyColumn.getColumnName());
            deleteSb.append("=");
            deleteSb.append("'");
            if (StringUtils.isNotEmpty(params.getString(primaryKeyColumn.getColumnSaveAs()))) {
                deleteSb.append(params.getString(primaryKeyColumn.getColumnSaveAs()));
            } else {
                if (StringUtils.isNotEmpty(params.getString(primaryKeyColumn.getColumnName()))) {
                    deleteSb.append(params.getString(primaryKeyColumn.getColumnName()));
                }
            }
            deleteSb.append("'");
            MyConnection connect = new DBUtils().getConnect(datasource);
            try {
                connect.excute(deleteSb.toString());
            } catch (Exception e) {
                throw new CustomException("来自模拟中台的提示: " + e.getMessage());
            }
        } else {
            throw new CustomException("来自模拟中台的提示: 无效的参数");
        }

    }

    private String baseQuerySql(List<TbColumn> list) {
        StringBuffer sb = new StringBuffer();
        for (TbColumn tbColumn : list) {
            if (StringUtils.equalsAnyIgnoreCase(tbColumn.getColumnType(), "timestamp")) {
                sb.append(" (to_char(");
                sb.append(tbColumn.getColumnName());
                sb.append(", 'YYYY-MM-DD HH24:MI:SS')");
                sb.append(")");
                if (StringUtils.isNotEmpty(tbColumn.getColumnSaveAs())) {
                    sb.append(" AS ");
                    sb.append("\"").append(tbColumn.getColumnSaveAs()).append("\"");
                } else {
                    sb.append(" AS ");
                    sb.append("\"").append(tbColumn.getColumnName()).append("\"");
                }
            } else {
                sb.append(tbColumn.getColumnName());
                if (StringUtils.isNotEmpty(tbColumn.getColumnSaveAs())) {
                    sb.append(" AS ");
                    sb.append("\"").append(tbColumn.getColumnSaveAs()).append("\"");
                }
            }
            sb.append(",");
        }
        return sb.toString();
    }

    private TbColumn getColumnBySaveAs(List<TbColumn> list, String s) {
        for (TbColumn tbColumn : list) {
            if (StringUtils.isNotEmpty(tbColumn.getColumnSaveAs())) {
                if (s.equals(tbColumn.getColumnSaveAs())) {
                    return tbColumn;
                }
            } else {
                if (s.equalsIgnoreCase(tbColumn.getColumnName())) {
                    return tbColumn;
                }
            }
        }
        return null;
    }

    private StringBuffer buildFilter(JSONArray filters) {
        StringBuffer whereBuilder = new StringBuffer(" where 1=1 ");
        for (Object o : filters) {
            JSONObject filter = JSONObject.parseObject(JSON.toJSONString(o));
            String fieldName = filter.getString("fieldName");
            String compare = filter.getString("compare");
            String fieldValue = filter.getString("fieldValue");
            TbColumn columnBySaveAs;
            if (StringUtils.isNotEmpty(fieldName)) {
                columnBySaveAs = getColumnBySaveAs(list, fieldName);
            } else {
                continue;
            }

            if (ObjectUtils.isEmpty(columnBySaveAs)) {
                String tableName = CollectionUtils.isEmpty(list) ? " " : list.get(0).getTableName();
                throw new CustomException("来自模拟中台的提示: 表 [" + tableName + "] 字段 [" + fieldName + "] 未保存");
            }

            if (StringUtils.equalsAny(compare.trim(), "=", ">=", "<=", ">", "<")) {
                whereBuilder.append(" AND ");
                if (ObjectUtils.isEmpty(columnBySaveAs)) {
                    whereBuilder.append(fieldName).append(" ");
                } else {
                    whereBuilder.append(columnBySaveAs.getColumnName()).append(" ");
                }

                whereBuilder.append(compare).append(" ");
                whereBuilder.append("'").append(fieldValue).append("' ");
            }

            if ("in".equalsIgnoreCase(compare.trim()) || "not in".equalsIgnoreCase(compare.trim())) {
                whereBuilder.append(" AND ");
                if (ObjectUtils.isEmpty(columnBySaveAs)) {
                    whereBuilder.append(fieldName).append(" ");
                } else {
                    whereBuilder.append(columnBySaveAs.getColumnName()).append(" ");
                }
                whereBuilder.append(compare).append(" ");
                whereBuilder.append("(");

                String[] split = fieldValue.split(",");

                Iterator<String> iterator = Arrays.stream(split).iterator();
                while (iterator.hasNext()) {
                    whereBuilder.append("'").append(iterator.next()).append("'");
                    if (iterator.hasNext()) {
                        whereBuilder.append(", ");
                    }
                }
                whereBuilder.append(")");
            }

            if ("like".equalsIgnoreCase(compare.trim()) || "not like".equalsIgnoreCase(compare.trim())) {
                whereBuilder.append(" AND ");
                if (ObjectUtils.isEmpty(columnBySaveAs)) {
                    whereBuilder.append(fieldName).append(" ");
                } else {
                    whereBuilder.append(columnBySaveAs.getColumnName()).append(" ");
                }

                whereBuilder.append(compare).append(" ");
                whereBuilder.append("'%").append(fieldValue).append("%' ");
            }
        }
        return whereBuilder;
    }

    /**
     * 查询已认证人员
     *
     * @return
     */
    @PostMapping("/orgService/safePersonInfo/find")
    public String safePersonInfoList(@RequestBody BusinessCenterQueryParams queryParams) throws Exception {
        ClassPathResource resource = new ClassPathResource("analog/persons-access.txt");
        InputStream inputStream = resource.getInputStream();
        String str = new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining(System.lineSeparator()));
        JSONObject json = JSONObject.parseObject(str);
        JSONArray result = json.getJSONArray("result");
        List<Object> persons = result.stream().collect(Collectors.toList());
        Integer page = queryParams.getPage();
        Integer perPage = queryParams.getPerPage();
        if (page != null && perPage != null) {
            // 手动分页
            //起始下标
            int fromIndex = perPage * (page - 1);
            //终止下标
            int toIndex = fromIndex + perPage;
            int total = persons.size();
            if (toIndex >= total) {
                toIndex = total;
            }
            persons = persons.subList(fromIndex, toIndex);
        }
        JSONObject obj = new JSONObject();
        obj.put("root", persons);
        json.put("result", obj);
        return json.toJSONString();
    }

    /**
     * 模拟分包单位获取
     */
    @PostMapping("/ticketWork/SfbSafPlanRelOrg/find")
    public String findSfbSafPlanRelOrg(@RequestBody JSONObject data) throws IOException {
        JSONObject object = JSON.parseObject(new BufferedReader(new InputStreamReader(new ClassPathResource("mockData/relOrgs.json").getInputStream()))
                .lines().collect(Collectors.joining(System.lineSeparator())));
        return JSON.toJSONString(object);
    }

    @PostMapping("/Organize/virtualOrg/getVirtualInfoByUserNameByType")
    public String getVirtualInfoByUserNameByType(@RequestBody JSONObject data) {
        return "{\n" +
                "    \"result\": [\n" +
                "    ],\n" +
                "    \"message\": \"\",\n" +
                "    \"errors\": \"\",\n" +
                "    \"status\": \"000000\"\n" +
                "}";
    }


}
